package vn.intelsoft.vlogvn.instance;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public final class BitmapUtils {
	private static final String TAG = "Memory Cache";
	public static HashMap<String, Bitmap> datas = new HashMap<String, Bitmap>();
	
	@SuppressLint("SdCardPath")
	public static Bitmap get(Context c, String path) {
        synchronized (datas) {
            if (!datas.containsKey(path)) {
                try {
                    Bitmap bitmap = null;
                    	bitmap = Instance.decodeFileBase(new File(path));
                    	
                    datas.put(path, bitmap);
                } catch (Exception e) {
                    Log.e(TAG, "Could not get Bitmap '" + path
                            + "' because " + e.getMessage());
                    return null;
                }
            }
            return datas.get(path);
        }
    }
	
	public static void removeAll() {
		List<String> keys = new ArrayList<String>(datas.keySet());
		Log.d("into recycle", "remove all" + keys.size() + ", " + datas.size());
		for(int i = 0; i < keys.size(); i ++) {
			if(datas.get(keys.get(i)) != null) {
				datas.get(keys.get(i)).recycle();
				datas.remove(keys.get(i));
				Log.d("recycle", "index " + i);
			}
		}
		
		datas = new HashMap<String, Bitmap>();
	}
	
	public static void remove(String path) {
		try {
			datas.get(path).recycle();
			datas.remove(path);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Bitmap loadAsset( Context context, String assetName ) {
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			is = context.getAssets().open( assetName );
			bitmap = BitmapFactory.decodeStream( is );
		} catch (Exception e)
		{
			Log.e( TAG, "Load Error", e );
		} finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				} catch (Exception e)
				{
				}
			}
		}
		return bitmap;
	}
}
